#include "Keyboard.h"
#include "InputDefs.h"
#include "Logger\Logger.h"

#if defined (_DEBUG)
#include "Memory\MemLeaks.h"
#endif

//-------------------------------------------------
CKeyboard::CKeyboard()
{
	memset(m_Keys, 0, sizeof(m_Keys));
	memset(m_KeysOld, 0, sizeof(m_KeysOld));
}

//-------------------------------------------------
CKeyboard::~CKeyboard()
{

}

//-------------------------------------------------
bool CKeyboard::Initialize(LPDIRECTINPUT8 _directInput, HWND _hWnd)
{
	bool l_bIsOk;

	l_bIsOk = CInputDevice::Initialize(_directInput, _hWnd, GUID_SysKeyboard, &c_dfDIKeyboard);

	if(l_bIsOk)
	{
		// clear out the structs
		memset(m_Keys, 0, sizeof(m_Keys));
		memset(m_KeysOld, 0, sizeof(m_KeysOld));

		// acquire the device to make it work
		m_DIDevice->Acquire();
	}
	else
	{
		CInputDevice::Uninitialize();
	}

	return l_bIsOk;
}

//-------------------------------------------------
bool CKeyboard::Update()
{
	bool l_bIsOk;

	// copy keyboard state from last frame
	memcpy(m_KeysOld, m_Keys, sizeof(m_Keys));

	l_bIsOk = GetData(Input::IDV_KEYBOARD, &m_Keys[0], NULL);

	// try to get the data from the keyboard
	if (!l_bIsOk) 
	{
		LOGGER->AddNewLog(ELL_ERROR, "CKeyboard::Update-> GetData failed");
	}

	return l_bIsOk;
}

//-------------------------------------------------
bool CKeyboard::IsDown(uint32 nID) const
{
	// translate virtual code to scan code
	if (m_Keys[nID] & 0x80)
		return true;

	return false;
}

//-------------------------------------------------
bool CKeyboard::IsDownUp(uint32 nID) const
{
	// translate virtual code to scan code
	if ( (m_KeysOld[nID]&0x80) && !(m_Keys[nID]&0x80) )
		return true;

	return false;
}

//-------------------------------------------------
bool CKeyboard::IsUpDown(uint32 nID) const
{
	// translate virtual code to scan code
	if ( !(m_KeysOld[nID]&0x80) && (m_Keys[nID]&0x80) )
		return true;

	else return false;
}